
import * as types from './mutation-types'
import store from './store'
import ws from '../utils/websocket'
import {getUserInfo,getPermissions,getDevices,getPositions,getDeviceTypes,getCommandViews} from '../api/api';

export default {

	initData({ commit },context){
			store.dispatch('initGlobalPropertys',[{key:'isLogin',value:true}])
			getUserInfo().then((data) => {
						commit(types.INIT_USER_INFO, data.user)
						commit(types.SET_UNREAD_COUNT, data.messages.unReadEventCount)
						getPermissions().then((data) => {
									commit(types.INIT_USER_PERMISSIONS, data)
									getDevices().then((data) => {
												commit(types.INIT_USER_DEVICES, data)
												getPositions().then((data) => {
															commit(types.UPDATE_DEVICE_POSITION, data)
															ws.init(context);
															getDeviceTypes().then((data) => {
											  						//commit(types.INIT_STATIC_DATA, {deviceTypes:data});
																		var deviceTypes = data;
																		var commands = [];
															  		var cmdIds = [];
																		getCommandViews().then((data) => {
																					data.views.forEach(command => {
																						 commands[command.id] = command
																					});
																					data.commandIdsByType.forEach(row => {
																						 cmdIds[row.typeId] = row.commandIds.split(',')
																					});
														  						commit(types.INIT_STATIC_DATA, {commands:commands,ids:cmdIds,deviceTypes:deviceTypes});
														  			});
											  			});
												});
									});
						});
			});
	},
	initGlobalPropertys({ commit },props){
			commit(types.INIT_GLOBAL_PROPERTYS,props)
	},
	setSelectDeviceId({ commit }, index) {
  		commit(types.SET_SELECT_DEVICE_ID, index)
  },
	updateDevicePosition({ commit }, positions) {
  		commit(types.UPDATE_DEVICE_POSITION, positions)
  },
	updateDeviceStatus({ commit }, status) {
  		commit(types.UPDATE_DEVICE_STATUS, status)
  },
	setMapValue({ commit },props) {
		commit(types.SET_MAP_VALUE,props);
	},
	exit({ commit }) {
		commit(types.INIT_USER_INFO, {})
		commit(types.INIT_GLOBAL_PROPERTYS,[{key:'isLogin',value:false}])
		ws.close();
	},
	isShowBoubble({ commit }) {
  		commit(types.USER_IS_SHOW_BUBBLE)
  	},
	initDevices({ commit }){
		getDevices().then((data) => {
					commit(types.INIT_USER_DEVICES, data)
					getPositions().then((data) => {
								commit(types.UPDATE_DEVICE_POSITION, data)
					});
		});
	},
};
